package com.example.mqtt.mq;

import com.example.mqtt.config.MqttConfig;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/4/21 20:14
 **/
@Slf4j
@Component
public class MqttPublisher {

    @Autowired
    private MqttConfig mqttConfig;

    public void sendMessage(String topic, String message) {
        Mqtt5AsyncClient mqttClient = mqttConfig.mqttClient();
        mqttClient.publishWith()
                .topic(topic)
                .payload(message.getBytes())
                .qos(MqttQos.AT_LEAST_ONCE)
                .send()
                .whenComplete((publish, throwable) -> {
                    if (throwable != null) {
                        log.warn("消息发送失败: {}", throwable.getMessage());
                    } else {
                        log.info("消息已发送 [主题: {},{}]: ", topic, message);
                    }
                });
    }
}
